package com.heba.greenmulu.scan;

import android.graphics.Typeface;
import android.os.Bundle;

import androidx.annotation.Dimension;
import androidx.annotation.NonNull;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.heba.Cfg;
import com.heba.adapter.ItemComparisonAdapter;
import com.heba.config.CommonConfig;
import com.heba.bean.product.ItemProductCompareObject;
import com.heba.bean.PhotoObject;
import com.heba.bean.product.ProductContentObject;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ZoomPhotoActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.IndicatorLineUtil;
import com.heba.utils.ToastShow;
import com.heba.utils.UniversalImageLoadTool;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 扫描食品含量对比页面
 * <p>
 * Created by jason on 2019/2/26.
 */

public class ItemComparisoActivity extends BaseActivity {

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ItemComparisonAdapter adapter;

    private boolean isFirstHeader;    //用于判断刷新头部
    private boolean isFirstSpinner;    //用于判断刷新头部的spinner，防止重复刷新数据
    private List<ItemProductCompareObject> headerList = new ArrayList<>();    //扫描列表，可能有大包装会存在多条信息
    private ItemProductCompareObject headerItemProductCompareObject = new ItemProductCompareObject();
    private List<ItemProductCompareObject> list = new ArrayList<>();
    private String productID = "";
    private String barCode = "";

    //产品比较参数
    private int type = 2;    //1表示比较 Per Serving, 2表示比较 Per 100g/ml, 3表示比较 Whole Pack
    private int isEnergy = 0;
    private int isProtein = 0;
    private int isFat = 0;
    private int isSatFat = 0;
    private int isCarb = 0;
    private int isSugar = 0;
    private int isSodium = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_comparison);
        init();
        initTopbar();
        findViewById();
        initView();
        getProductContentData();
    }

    /**
     * 初始化
     */
    private void init() {
        isFirstHeader = true;
        isFirstSpinner = true;
        Cfg.getProductRecord();
        isEnergy = Cfg.isEnergy;
        isProtein = Cfg.isProtein;
        isFat = Cfg.isFat;
        isSatFat = Cfg.isSatFat;
        isCarb = Cfg.isCarb;
        isSugar = Cfg.isSugar;
        isSodium = Cfg.isSodium;
    }

    /**
     * 多包装时，下拉选择产品
     */
    private void addSpinnerData(Spinner mSpinner) {
        //原始string数组
        final String[] spinnerItems = new String[headerList.size()];
        if (!headerList.isEmpty()) {
            for (int i = 0; i < headerList.size(); i++) {
                spinnerItems[i] = headerList.get(i).getFlavorName();
            }
        }

        //简单的string数组适配器：样式res，数组
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, spinnerItems);
        //下拉的样式res
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        mSpinner.setAdapter(spinnerAdapter);
        //选择监听
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                //设置spinner内的填充文字居中
//                ((TextView) view).setGravity(Gravity.CENTER);
                headerItemProductCompareObject = headerList.get(pos);
                getProductSimilarData(headerItemProductCompareObject.getProductID());
                isFirstHeader = true;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            productID = bundle.getString(CommonConfig.PRODUCT_ID, "");
            barCode = bundle.getString(CommonConfig.BARCODE, "");
        }

        txt_title.setText(getResources().getString(R.string.comparison));
        img_right.setImageResource(R.drawable.icon_information);

        img_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(ItemProductInfomationActivity.class);
            }
        });

        adapter = new ItemComparisonAdapter(this, list) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, ItemProductCompareObject data, int position) {
                if (holder instanceof HeaderHolder) {
                    if (isFirstHeader) {
                        isFirstHeader = false;
                        HeaderHolder headerHolder = (HeaderHolder) holder;
                        if (null != headerItemProductCompareObject) {
                            if (!headerList.isEmpty() && headerList.size() == 1) {
                                headerHolder.spinner.setVisibility(View.GONE);
                            } else {
                                if (isFirstSpinner) {
                                    isFirstSpinner = false;
                                    headerHolder.spinner.setVisibility(View.VISIBLE);
                                    addSpinnerData(headerHolder.spinner);
                                }
                            }
                            //添加产品信息
//                            UniversalImageLoadTool.disPlay(headerItemProductCompareObject.getIcon(), headerHolder.img_photo, R.drawable.btn_upload_image);
//                            headerHolder.txt_title.setText(headerItemProductCompareObject.getBrandName());
//                            headerHolder.txt_content.setText(headerItemProductCompareObject.getProductName());
//                            headerHolder.txt_serving_size.setText(String.format(getResources().getString(R.string.per_serving_size), headerItemProductCompareObject.
//                                    getPackageSize(), headerItemProductCompareObject.getPackageUnit(), CommonUtils.subZeroAndDot(headerItemProductCompareObject.getServingSize()), headerItemProductCompareObject.getServingSizeUnit()));
//                            headerHolder.img_collect.setSelected(headerItemProductCompareObject.getIsCollect() == 1 ? true : false);

                            //tab标签
                            String[] strings = getResources().getStringArray(R.array.array_per);

                            /**
                             * 添加tab
                             */
                            headerHolder.tabLayout.removeAllTabs();
                            for (int i = 0; i < strings.length; i++) {
                                headerHolder.tabLayout.addTab(headerHolder.tabLayout.newTab().setText(strings[i]));
                            }

                            /**
                             * 设置指示线长度间隔(单位dp)
                             */
                            headerHolder.tabLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    IndicatorLineUtil.setIndicator(headerHolder.tabLayout, 0, 0);
                                }
                            });

                            /**
                             * 默认选中第二个选项卡
                             */
                            headerHolder.tabLayout.getTabAt(1).select();
                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getPergmlObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());

                            /**
                             * 监听tablayout
                             */
                            headerHolder.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                                @Override
                                public void onTabSelected(TabLayout.Tab tab) {
                                    switch (tab.getPosition()) {
                                        case 0:
                                            type = 1;
                                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getPerServingObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());
                                            getProductSimilarData(headerItemProductCompareObject.getProductID());
                                            break;
                                        case 1:
                                            type = 2;
                                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getPergmlObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());
                                            getProductSimilarData(headerItemProductCompareObject.getProductID());
                                            break;
                                        case 2:
                                            type = 3;
                                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getWholePackObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());
                                            getProductSimilarData(headerItemProductCompareObject.getProductID());
                                            break;
                                        default:
                                            break;
                                    }
                                }

                                @Override
                                public void onTabUnselected(TabLayout.Tab tab) {

                                }

                                @Override
                                public void onTabReselected(TabLayout.Tab tab) {

                                }
                            });

                            /**
                             * 查看大图
                             */
//                            headerHolder.img_photo.setOnClickListener(v -> {
//                                if (!headerItemProductCompareObject.getProductImageList().isEmpty()) {
//                                    Bundle bundle1 = new Bundle();
//                                    bundle1.putSerializable(CommonConfig.PHOTOLIST, (Serializable) headerItemProductCompareObject.getProductImageList());
//                                    openActivity(ZoomPhotoActivity.class, bundle1);
//                                }
//                            });

                            /**
                             * 收藏
                             */
//                            headerHolder.img_collect.setOnClickListener(v -> {
//                                if (headerItemProductCompareObject.getIsCollect() == 1) {
//                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
//                                        @Override
//                                        public void Success() {
//                                            headerItemProductCompareObject.setIsCollect(0);
//                                            headerHolder.img_collect.setSelected(false);
//                                        }
//
//                                        @Override
//                                        public void Fail(String error) {
//                                        }
//                                    }).uncollectProduct(ItemComparisoActivity.this, headerItemProductCompareObject.getProductID());
//                                } else {
//                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
//                                        @Override
//                                        public void Success() {
//                                            headerItemProductCompareObject.setIsCollect(1);
//                                            headerHolder.img_collect.setSelected(true);
//                                        }
//
//                                        @Override
//                                        public void Fail(String error) {
//                                        }
//                                    }).collectProduct(ItemComparisoActivity.this, headerItemProductCompareObject.getProductID());
//                                }
//                            });

                            /**
                             * 分享
                             */
//                            headerHolder.img_share.setOnClickListener(v -> {
//                                /**
//                                 * 调用系统分享
//                                 */
//                                Intent shareIntent = new Intent(Intent.ACTION_SEND);
//                                shareIntent.setType("text/*");
////                                shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share));//添加分享内容标题
//                                shareIntent.putExtra(Intent.EXTRA_TEXT, headerItemProductCompareObject.getProductName() + " " + headerItemProductCompareObject.getLink());  //添加分享内容
//                                startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share)));
//                            });

                            /**
                             * 报告错误
                             */
//                            headerHolder.img_report.setOnClickListener(v -> {
//                                new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
//                                    @Override
//                                    public void onYesClick() {
//                                        Bundle bundle1 = new Bundle();
//                                        bundle1.putString(CommonData.PRODUCT_ID, headerItemProductCompareObject.getProductID());
//                                        openActivity(ItemReportProductActivity.class, bundle1);
//                                    }
//
//                                    @Override
//                                    public void onNoClick() {
//
//                                    }
//                                }).showDialog(ItemComparisoActivity.this, getResources().getString(R.string.report_error_tips), "");
//                            });

                            /**
                             * 产品对比参数选择
                             */
                            headerHolder.txt_less_energy.setSelected(isEnergy == 0 ? false : true);
                            headerHolder.txt_more_protein.setSelected(isProtein == 0 ? false : true);
                            headerHolder.txt_less_fat.setSelected(isFat == 0 ? false : true);
                            headerHolder.txt_less_sat_fat.setSelected(isSatFat == 0 ? false : true);
                            headerHolder.txt_less_carb.setSelected(isCarb == 0 ? false : true);
                            headerHolder.txt_less_sugar.setSelected(isSugar == 0 ? false : true);
                            headerHolder.txt_less_sodium.setSelected(isSodium == 0 ? false : true);
                            headerHolder.txt_less_energy.setOnClickListener(v -> {
                                headerHolder.txt_less_energy.setSelected(headerHolder.txt_less_energy.isSelected() ? false : true);
                                isEnergy = headerHolder.txt_less_energy.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_more_protein.setOnClickListener(v -> {
                                headerHolder.txt_more_protein.setSelected(headerHolder.txt_more_protein.isSelected() ? false : true);
                                isProtein = headerHolder.txt_more_protein.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_fat.setOnClickListener(v -> {
                                headerHolder.txt_less_fat.setSelected(headerHolder.txt_less_fat.isSelected() ? false : true);
                                isFat = headerHolder.txt_less_fat.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_sat_fat.setOnClickListener(v -> {
                                headerHolder.txt_less_sat_fat.setSelected(headerHolder.txt_less_sat_fat.isSelected() ? false : true);
                                isSatFat = headerHolder.txt_less_sat_fat.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_carb.setOnClickListener(v -> {
                                headerHolder.txt_less_carb.setSelected(headerHolder.txt_less_carb.isSelected() ? false : true);
                                isCarb = headerHolder.txt_less_carb.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_sugar.setOnClickListener(v -> {
                                headerHolder.txt_less_sugar.setSelected(headerHolder.txt_less_sugar.isSelected() ? false : true);
                                isSugar = headerHolder.txt_less_sugar.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_sodium.setOnClickListener(v -> {
                                headerHolder.txt_less_sodium.setSelected(headerHolder.txt_less_sodium.isSelected() ? false : true);
                                isSodium = headerHolder.txt_less_sodium.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });
                        }
                    }
                } else if (holder instanceof ItemHolder) {
                    ItemHolder itemHolder = (ItemHolder) holder;
                    itemHolder.constrain_view.setVisibility(View.VISIBLE);
                    itemHolder.constrain_view1.setVisibility(View.GONE);
                    UniversalImageLoadTool.disPlay(data.getIcon(), itemHolder.img_photo, R.drawable.btn_upload_image);
                    UniversalImageLoadTool.disPlay(data.getIcon(), itemHolder.img_photo1, R.drawable.btn_upload_image);
                    itemHolder.txt_product.setText(data.getBrandName());
                    itemHolder.txt_product1.setText(data.getBrandName());
                    itemHolder.txt_content.setText(data.getProductName());
                    itemHolder.txt_content1.setText(data.getProductName());
                    itemHolder.txt_serving_size.setText(String.format(getResources().getString(R.string.per_serving_size), data.
                            getPackageSize(), data.getPackageUnit(), CommonUtils.subZeroAndDot(data.getServingSize()), data.getServingSizeUnit()));
//                    itemHolder.img_collect.setSelected(data.getIsCollect() == 1 ? true : false);

                    /**
                     * 加载含量，此方法过于耗时
                     */
                    updatePerView(itemHolder.linear_per_view, data.getPergmlObject(), type, Float.valueOf(data.getServingSize()),
                            Float.valueOf(data.getPackageSize()), headerItemProductCompareObject.isFood());

                    /**
                     * 查看大图
                     */
                    itemHolder.img_photo1.setOnClickListener(v -> {
                        if (!data.getProductImageList().isEmpty()) {
                            Bundle bundle1 = new Bundle();
                            bundle1.putSerializable(CommonConfig.PHOTOLIST, (Serializable) data.getProductImageList());
                            openActivity(ZoomPhotoActivity.class, bundle1);
                        }
                    });

                    /**
                     * 收藏
                     */
//                    itemHolder.img_collect.setOnClickListener(v -> {
//                        if (data.getIsCollect() == 1) {
//                            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
//                                @Override
//                                public void Success() {
//                                    data.setIsCollect(0);
//                                    itemHolder.img_collect.setSelected(false);
//                                }
//
//                                @Override
//                                public void Fail(String error) {
//                                }
//                            }).uncollectProduct(ItemComparisoActivity.this, data.getProductID());
//                        } else {
//                            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
//                                @Override
//                                public void Success() {
//                                    data.setIsCollect(1);
//                                    itemHolder.img_collect.setSelected(true);
//                                }
//
//                                @Override
//                                public void Fail(String error) {
//                                }
//                            }).collectProduct(ItemComparisoActivity.this, data.getProductID());
//                        }
//                    });

                    /**
                     * 报告错误
                     */
//                    itemHolder.img_report.setOnClickListener(v -> {
//                        new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
//                            @Override
//                            public void onYesClick() {
//                                Bundle bundle1 = new Bundle();
//                                bundle1.putString(CommonData.PRODUCT_ID, data.getProductID());
//                                openActivity(ItemReportProductActivity.class, bundle1);
//                            }
//
//                            @Override
//                            public void onNoClick() {
//
//                            }
//                        }).showDialog(ItemComparisoActivity.this, getResources().getString(R.string.report_error_tips), "");
//                    });

                    /**
                     * 调用系统分享
                     */
//                    itemHolder.img_share.setOnClickListener(v -> {
//                        Intent shareIntent = new Intent(Intent.ACTION_SEND);
//                        shareIntent.setType("text/*");
////                        shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share));//添加分享内容标题
//                        shareIntent.putExtra(Intent.EXTRA_TEXT, data.getProductName() + " " + data.getLink());  //添加分享内容
//                        startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share)));
//                    });

                    /**
                     * 显示大布局
                     */
                    itemHolder.constrain_view.setOnClickListener(v -> {
                        itemHolder.constrain_view.setVisibility(View.GONE);
                        itemHolder.constrain_view1.setVisibility(View.VISIBLE);
                    });

                    /**
                     * 显示小布局
                     */
                    itemHolder.constrain_view1.setOnClickListener(v -> {
                        itemHolder.constrain_view.setVisibility(View.VISIBLE);
                        itemHolder.constrain_view1.setVisibility(View.GONE);
                    });
                }
            }
        };
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(adapter);
        recyclerView.setItemViewCacheSize(30);
        recyclerView.setDrawingCacheEnabled(true);
        recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

        /**
         * 增加额外缓存空间
         * 显示范围之外，应该额外缓存的空间
         */
        new LinearLayoutManager(this) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 200;
            }
        };

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                Page = 1;
                isRefreshFromTop = true;
            }
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                Page++;
                isRefreshFromTop = false;
            }
        });
    }

    /**
     * 比較營養素含量，顯示紅綠燈等級
     *
     * @param linearLayout  view
     * @param contentObject 含量數據,用於比較
     * @param type          1:每食用分量  2:每100g/ml  3:整個包裝
     * @param servingSize   食用分量
     * @param packageSize   整個包裝
     * @param isFood        食物还是饮料(所含标准不同)
     */
    private void updatePerView(LinearLayout linearLayout, ProductContentObject contentObject, int type, float servingSize, float packageSize, boolean isFood) {
        linearLayout.removeAllViews();
        /**
         * 計算含量標準
         */
        double fat = 0.0d, satFat = 0.0d, sugar = 0.0d, sodium = 0.0d;
        switch (type) {
            case 1:
                if (servingSize != 0) {
                    fat = (100 / servingSize) * contentObject.getFat();
                    satFat = (100 / servingSize) * contentObject.getSatFat();
                    sugar = (100 / servingSize) * contentObject.getSugar();
                    sodium = (100 / servingSize) * contentObject.getSodium();
                }
                break;
            case 2:
                fat = contentObject.getFat();
                satFat = contentObject.getSatFat();
                sugar = contentObject.getSugar();
                sodium = contentObject.getSodium();
                break;
            case 3:
                if (packageSize != 0) {
                    fat = (100 / packageSize) * contentObject.getFat();
                    satFat = (100 / packageSize) * contentObject.getSatFat();
                    sugar = (100 / packageSize) * contentObject.getSugar();
                    sodium = (100 / packageSize) * contentObject.getSodium();
                }
                break;
            default:
                break;
        }

        /**
         * 添加營養桶
         */
        for (int i = 0; i < 7; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_per_image, null);
            ImageView imageView = view.findViewById(R.id.img_per_bg);
            TextView txt_text1 = view.findViewById(R.id.txt_text1);
            TextView txt_text2 = view.findViewById(R.id.txt_text2);
            TextView txt_text3 = view.findViewById(R.id.txt_text3);
            TextView txt_unit = view.findViewById(R.id.txt_unit);
            TextView txt_percent = view.findViewById(R.id.txt_percent);
            imageView.setImageResource(R.drawable.icon_s_gray);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((DensityUtils.getWidth(this) - DensityUtils.dip2px(this, 20)) / 7,
                    DensityUtils.dip2px(this, 72));
            view.setLayoutParams(params);
            switch (i) {
                case 0:
                    txt_text1.setTextSize(Dimension.SP, 10);
                    txt_text1.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    txt_text1.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getEnergy())));
                    txt_text2.setVisibility(View.GONE);
                    txt_unit.setText(getResources().getString(R.string.kcal));
                    if (contentObject.getEnergyPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getEnergyPercent()));
                    }
                    break;
                case 1:
                    txt_text1.setText(getResources().getString(R.string.protein));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getProtein())));
                    txt_unit.setText("g");
                    if (contentObject.getProteinPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getProteinPercent()));
                    }
                    break;
                case 2:
                    txt_text1.setText(getResources().getString(R.string.fat));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getFat())));
                    txt_unit.setText("g");
                    if (contentObject.getFatPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getFatPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (fat <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (fat > 0.5 && fat <= 3) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (fat > 3 && fat <= 17.5) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (fat > 17.5) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (fat <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (fat > 0.5 && fat <= 1.5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (fat > 1.5 && fat <= 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (fat > 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                case 3:
                    txt_text1.setText(getResources().getString(R.string.satfat));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getSatFat())));
                    txt_unit.setText("g");
                    if (contentObject.getSatFatPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getSatFatPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (satFat <= 0.1) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (satFat > 0.1 && satFat <= 1.5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (satFat > 1.5 && satFat <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (satFat > 5) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (satFat <= 0.1) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (satFat > 0.1 && satFat <= 0.75) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (satFat > 0.75 && satFat <= 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (satFat > 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                case 4:
                    txt_text1.setText(getResources().getString(R.string.carb));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getCarbs())));
                    txt_unit.setText("g");
                    if (contentObject.getCarbsPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getCarbsPercent()));
                    }
                    break;
                case 5:
                    txt_text1.setText(getResources().getString(R.string.sugar));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getSugar())));
                    txt_unit.setText("g");
                    if (contentObject.getSugarPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getSugarPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (sugar <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sugar > 0.5 && sugar <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sugar > 5 && sugar <= 22.5) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sugar > 22.5) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (sugar <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sugar > 0.5 && sugar <= 2.5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sugar > 2.5 && sugar <= 11.25) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sugar > 11.25) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                case 6:
                    txt_text1.setText(getResources().getString(R.string.sodium));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getSodium())));
                    txt_unit.setText("mg");
                    if (contentObject.getSodiumPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getSodiumPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (sodium <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sodium > 5 && sodium <= 120) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sodium > 120 && sodium <= 600) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sodium > 600) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (sodium <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sodium > 5 && sodium <= 120) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sodium > 120 && sodium <= 300) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sodium > 300) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                default:
            }
            linearLayout.addView(view);
        }
    }

    /**
     * 获取产品含量
     */
    private void getProductContentData() {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Barcode", barCode);
        params.put("ProductID", productID);
        client.get(Cfg.BaseUrl + "/Product/Comparison", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateProductContentData(array);
                            } else {
                                ToastShow.displayToast(ItemComparisoActivity.this, getResources().getString(R.string.finish_no_data));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * updateProductContentData
     *
     * @param data
     */
    private void updateProductContentData(JSONArray data) {

        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemProductCompareObject itemProductCompareObject = new ItemProductCompareObject();
                itemProductCompareObject.setProductID(object.getString("ProductID"));
                itemProductCompareObject.setProductName(object.getString("ProductName"));
                itemProductCompareObject.setBrandName(object.getString("BrandName"));
                itemProductCompareObject.setCatName(object.getString("CatName"));
                itemProductCompareObject.setIcon(object.getString("Icon"));
                itemProductCompareObject.setFlavorName(object.getString("FlavorName"));
                itemProductCompareObject.setPackageSize(object.getString("PackageSize"));
                itemProductCompareObject.setServingSize(object.getString("ServingSize"));
                itemProductCompareObject.setValuePerUnit(object.getString("ValuePerUnit"));
                itemProductCompareObject.setPackageUnit(object.getString("PackageUnit"));
                itemProductCompareObject.setServingSizeUnit(object.getString("ServingSizeUnit"));
                itemProductCompareObject.setIsCollect(object.getInt("IsCollect"));
                if (object.has("Link"))
                    itemProductCompareObject.setLink(object.getString("Link"));
                itemProductCompareObject.setFood(object.getString("Type").equals("1") ? false : true);
                if (object.has("PerServing")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("PerServing");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    itemProductCompareObject.setPerServingObject(contentObject1);
                }

                if (object.has("Pergml")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("Pergml");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    itemProductCompareObject.setPergmlObject(contentObject1);
                }

                if (object.has("WholePack")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("WholePack");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    itemProductCompareObject.setWholePackObject(contentObject1);
                }

                if (object.has("ProductImageList")) {
                    JSONArray array = object.getJSONArray("ProductImageList");
                    if (array.length() > 0) {
                        List<PhotoObject> photoObjects = new ArrayList<>();
                        for (int j = 0; j < array.length(); j++) {
                            JSONObject object1 = array.getJSONObject(j);
                            PhotoObject photoObject = new PhotoObject();
                            photoObject.setImageUrl(object1.getString("ImageUrl"));
                            photoObjects.add(photoObject);
                        }
                        itemProductCompareObject.setProductImageList(photoObjects);
                    }
                }
                headerList.add(itemProductCompareObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        /**
         * 获取产品相似列表
         */
        if (!headerList.isEmpty()) {
            headerItemProductCompareObject = headerList.get(0);
            getProductSimilarData(headerItemProductCompareObject.getProductID());
        }

    }

    /**
     * getProductSimilarData
     * 获取产品对比列表
     */
    private void getProductSimilarData(String productID) {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Type", type);
        params.put("ProductID", productID);
        params.put("IsEnergy", isEnergy);
        params.put("IsProtein", isProtein);
        params.put("IsFat", isFat);
        params.put("IsSatFat", isSatFat);
        params.put("IsCarb", isCarb);
        params.put("IsSugar", isSugar);
        params.put("IsSodium", isSodium);
        client.get(Cfg.BaseUrl + "/Product/Similar", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();

                        if (!list.isEmpty() && list.size() > 0) {
                            list.clear();
                        }
                        //添加头部
                        list.add(new ItemProductCompareObject());

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateProductSimilarData(array);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * updateProductSimilarData
     *
     * @param data
     */
    private void updateProductSimilarData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemProductCompareObject compareObject = new ItemProductCompareObject();
                compareObject.setProductID(object.getString("ProductID"));
                compareObject.setProductName(object.getString("ProductName"));
                compareObject.setBrandName(object.getString("BrandName"));
                compareObject.setCatName(object.getString("CatName"));
                compareObject.setIcon(object.getString("Icon"));
                compareObject.setFlavorName(object.getString("FlavorName"));
                compareObject.setPackageSize(object.getString("PackageSize"));
                compareObject.setServingSize(object.getString("ServingSize"));
                compareObject.setValuePerUnit(object.getString("ValuePerUnit"));
                compareObject.setPackageUnit(object.getString("PackageUnit"));
                compareObject.setServingSizeUnit(object.getString("ServingSizeUnit"));
                compareObject.setIsCollect(object.getInt("IsCollect"));
                if (object.has("Link"))
                    compareObject.setLink(object.getString("Link"));

//                if (object.has("PerServing")) {
//                    ProductContentObject contentObject1 = new ProductContentObject();
//                    JSONObject object1 = object.getJSONObject("PerServing");
//                    contentObject1.setEnergy(object1.getDouble("Energy"));
//                    contentObject1.setProtein(object1.getDouble("Protein"));
//                    contentObject1.setFat(object1.getDouble("Fat"));
//                    contentObject1.setCarbs(object1.getDouble("Carbs"));
//                    contentObject1.setSugar(object1.getDouble("Sugar"));
//                    contentObject1.setSodium(object1.getDouble("Sodium"));
//                    contentObject1.setSatFat(object1.getDouble("SatFat"));
//                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
//                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
//                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
//                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
//                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
//                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
//                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
//                    compareObject.setPerServingObject(contentObject1);
//                }

                if (object.has("Pergml")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("Pergml");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    compareObject.setPergmlObject(contentObject1);
                }

//                if (object.has("WholePack")) {
//                    ProductContentObject contentObject1 = new ProductContentObject();
//                    JSONObject object1 = object.getJSONObject("WholePack");
//                    contentObject1.setEnergy(object1.getDouble("Energy"));
//                    contentObject1.setProtein(object1.getDouble("Protein"));
//                    contentObject1.setFat(object1.getDouble("Fat"));
//                    contentObject1.setCarbs(object1.getDouble("Carbs"));
//                    contentObject1.setSugar(object1.getDouble("Sugar"));
//                    contentObject1.setSodium(object1.getDouble("Sodium"));
//                    contentObject1.setSatFat(object1.getDouble("SatFat"));
//                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
//                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
//                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
//                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
//                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
//                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
//                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
//                    compareObject.setWholePackObject(contentObject1);
//                }

                if (object.has("ProductImageList")) {
                    JSONArray array = object.getJSONArray("ProductImageList");
                    if (array.length() > 0) {
                        List<PhotoObject> photoObjects = new ArrayList<>();
                        for (int j = 0; j < array.length(); j++) {
                            JSONObject object1 = array.getJSONObject(j);
                            PhotoObject photoObject = new PhotoObject();
                            photoObject.setImageUrl(object1.getString("ImageUrl"));
                            photoObjects.add(photoObject);
                        }
                        compareObject.setProductImageList(photoObjects);
                    }
                }
                list.add(compareObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /**
         * 保存筛选记录，下一次进入页面时默认筛选
         */
        Cfg.change("isEnergy", isEnergy);
        Cfg.change("isProtein", isProtein);
        Cfg.change("isFat", isFat);
        Cfg.change("isSatFat", isSatFat);
        Cfg.change("isCarb", isCarb);
        Cfg.change("isSugar", isSugar);
        Cfg.change("isSodium", isSodium);
        Cfg.save();
    }
}
